package com.wmh.baseservice.user.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wmh.baseservice.admin.pojo.AdGoods;
import com.wmh.baseservice.admin.pojo.AdProfit;
import com.wmh.baseservice.admin.service.AdGoodsService;
import com.wmh.baseservice.admin.service.AdProfitService;
import com.wmh.baseservice.common.ex.ServiceException;
import com.wmh.baseservice.common.mybatisplus.methods.CommonServiceImpl;
import com.wmh.baseservice.common.utils.CommUtil;
import com.wmh.baseservice.common.utils.UUIDUtil;
import com.wmh.baseservice.merchant.pojo.MerchantGoods;
import com.wmh.baseservice.merchant.pojo.MerchantIncomeExpend;
import com.wmh.baseservice.merchant.pojo.MerchantInfo;
import com.wmh.baseservice.skd.pojo.SkdGoodsSpec;
import com.wmh.baseservice.merchant.service.MerchantGoodsService;
import com.wmh.baseservice.merchant.service.MerchantIncomeExpendService;
import com.wmh.baseservice.merchant.service.MerchantInfoService;
import com.wmh.baseservice.skd.service.SkdGoodsSpecService;
import com.wmh.baseservice.system.pojo.SysMessage;
import com.wmh.baseservice.system.pojo.SysParams;
import com.wmh.baseservice.system.service.SysMessageService;
import com.wmh.baseservice.system.service.SysParamsService;
import com.wmh.baseservice.user.pojo.UsAddress;
import com.wmh.baseservice.user.pojo.UsGoodsOrder;
import com.wmh.baseservice.user.mapper.UsGoodsOrderMapper;
import com.wmh.baseservice.user.pojo.UsInfo;
import com.wmh.baseservice.user.service.UsAddressService;
import com.wmh.baseservice.user.service.UsGoodsOrderService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @author mmx generator
 * @since 2021-12-24
 */
@Service
public class UsGoodsOrderServiceImpl extends CommonServiceImpl<UsGoodsOrderMapper, UsGoodsOrder> implements UsGoodsOrderService {


    @Resource
    private SysMessageService sysMessageService;
    @Resource
    private UsGoodsOrderService usGoodsOrderService;
    @Resource
    private AdGoodsService adGoodsService;
    @Resource
    private MerchantGoodsService merchantGoodsService;
    @Resource
    private UsGoodsOrderMapper usGoodsOrderMapper;
    @Resource
    private UsAddressService usAddressService;
    @Resource
    private SkdGoodsSpecService merchantSpecService;
    @Resource
    private SysParamsService sysParamsService;
    @Resource
    private AdProfitService adProfitService;
    @Resource
    private MerchantIncomeExpendService merchantIncomeExpendService;
    @Resource
    private MerchantInfoService merchantInfoService;


    /**
     * 发货
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delivery(UsGoodsOrder usGoodsOrder) {
        if (!usGoodsOrderService.updateById(usGoodsOrder)) {
            throw new ServiceException();
        }
        SysMessage sysMessage = new SysMessage().setUsId(usGoodsOrder.getUsId()).setTitle("您的订单已发货").setContent("您订单号为:" + usGoodsOrder.getOrderNum() + "的商品已发货").setStatus(0);
        if (!sysMessageService.save(sysMessage)) {
            throw new ServiceException();
        }
    }

    /**
     * 购物车结算
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<String> shopCar(Long id, Long usId, JSONArray adGoodsArray, JSONArray merchantGoodsArray, List<AdGoods> adGoodsList, List<MerchantGoods> merchantGoodsList, List<SkdGoodsSpec> skdGoodsSpecList) {
        List<String> orderList = new ArrayList<>();
        if (adGoodsArray.size() != 0) {
            final BigDecimal[] totalPrice = {new BigDecimal(0)};
            UsGoodsOrder usGoodsOrder = new UsGoodsOrder();
            adGoodsArray.forEach(adGoods -> {
                JSONObject adGoodsObj = JSONObject.parseObject(adGoods.toString());
                BigDecimal price = adGoodsObj.getBigDecimal("price");
                Integer count = adGoodsObj.getInteger("count");
                BigDecimal multiply = price.multiply(BigDecimal.valueOf(count));
                totalPrice[0] = totalPrice[0].add(multiply);
            });
            usGoodsOrder.setSnapshot(adGoodsArray.toString());
            usGoodsOrder.setOrderNum(UUIDUtil.getTimeId() + UUIDUtil.getLetter());
            usGoodsOrder.setType(1);
            usGoodsOrder.setAddressId(id);
            usGoodsOrder.setTotalPrice(totalPrice[0]);
            usGoodsOrder.setRealPrice(totalPrice[0]);
            usGoodsOrder.setUsId(usId);
            usGoodsOrder.setStatus(0);
            if (!usGoodsOrderService.save(usGoodsOrder)) {
                throw new ServiceException();
            }
            orderList.add(usGoodsOrder.getOrderNum());
        }

        if (merchantGoodsArray.size() != 0) {
            merchantGoodsArray.forEach(merchantGoods -> {
                JSONObject merchantGoodsObj = JSONObject.parseObject(merchantGoods.toString());
                Long merchantId = merchantGoodsObj.getLong("merchantId");
                JSONArray shop = merchantGoodsObj.getJSONArray("shop");
                UsGoodsOrder usGoodsOrder = new UsGoodsOrder();
                usGoodsOrder.setMerchantId(merchantId);
                usGoodsOrder.setType(2);
                usGoodsOrder.setStatus(0);
                usGoodsOrder.setUsId(usId);
                usGoodsOrder.setAddressId(id);
                //计算总价
                final BigDecimal[] totalPrice = {new BigDecimal(0)};
                shop.forEach(item -> {
                    JSONObject object = JSONObject.parseObject(item.toString());
                    BigDecimal price = object.getBigDecimal("price");
                    Integer count = object.getInteger("count");
                    BigDecimal multiply = price.multiply(BigDecimal.valueOf(count));
                    totalPrice[0] = totalPrice[0].add(multiply);
                });
                usGoodsOrder.setTotalPrice(totalPrice[0]);
                usGoodsOrder.setRealPrice(totalPrice[0]);
                usGoodsOrder.setOrderNum(UUIDUtil.getTimeId() + UUIDUtil.getLetter());
                usGoodsOrder.setSnapshot(shop.toJSONString());
                if (!usGoodsOrderService.save(usGoodsOrder)) {
                    throw new ServiceException();
                }
                orderList.add(usGoodsOrder.getOrderNum());
            });
        }

        //规格扣减
        if (merchantGoodsList.size() != 0) {
            if (!merchantGoodsService.updateBatchById(merchantGoodsList)) {
                throw new ServiceException("修改普通商品库存错误");
            }
        }

        if (adGoodsList.size() != 0) {
            if (!adGoodsService.updateBatchById(adGoodsList)) {
                throw new ServiceException("修改平台商品库存错误");
            }
        }

        if (skdGoodsSpecList.size() != 0) {
            if (!merchantSpecService.updateBatchById(skdGoodsSpecList)) {
                throw new ServiceException("修改规格库存错误");
            }
        }

        return orderList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void balancePay(BigDecimal bigDecimal, UsInfo usInfo, JSONArray orderNumList) {
        //余额扣减
        usInfo.setBalance(usInfo.getBalance().subtract(bigDecimal));
        //订单状态修改
        orderNumList.forEach(item -> {
            UsGoodsOrder usGoodsOrder = usGoodsOrderService.getOneForUpdate(new QueryWrapper<UsGoodsOrder>().eq(UsGoodsOrder.ORDER_NUM, item));
            usGoodsOrder.setStatus(1);
            if (!usGoodsOrderService.updateById(usGoodsOrder)) {
                throw new ServiceException();
            }
        });

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelOrder(Long value) {
        usGoodsOrderMapper.cancelOrder(value);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(UsGoodsOrder usGoodsOrder, AdGoods adGoods, MerchantGoods merchantGoods, SkdGoodsSpec skdGoodsSpec, UsAddress usAddress) {
        //地址处理
        QueryWrapper<UsAddress> eq = new QueryWrapper<UsAddress>().eq(UsAddress.PROVINCE, usAddress.getProvince()).eq(UsAddress.CITY, usAddress.getCity()).eq(UsAddress.AREA, usAddress.getArea()).eq(UsAddress.ADDRESS, usAddress.getAddress()).eq(UsAddress.NAME, usAddress.getName())
                .eq(UsAddress.PHONE, usAddress.getPhone()).eq(UsAddress.US_ID, usAddress.getUsId());
        UsAddress oneForUpdate = usAddressService.getOneForUpdate(eq);
        if (!CommUtil.checkNull(oneForUpdate)) {
            if (!usAddressService.save(usAddress)) {
                throw new ServiceException();
            }
        } else {
            usGoodsOrder.setAddressId(oneForUpdate.getId());
        }
        //添加订单
        if (!save(usGoodsOrder)) {
            throw new ServiceException();
        }

        //扣减库存
        if (CommUtil.checkNull(skdGoodsSpec)) {
            if (!merchantSpecService.updateById(skdGoodsSpec)) {
                throw new ServiceException();
            }
        }

        if (CommUtil.checkNull(merchantGoods)) {
            if (!merchantGoodsService.updateById(merchantGoods)) {
                throw new ServiceException();
            }
        }

        if (CommUtil.checkNull(adGoods)) {
            if (!adGoodsService.updateById(adGoods)) {
                throw new ServiceException();
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void theGoods(UsGoodsOrder usGoodsOrder) {
        //修改订单状态
        if (!updateById(usGoodsOrder)) {
            throw new ServiceException();
        }
        //商家是否缴纳保证金，如缴纳，则直接将收益转入商家余额中，否则等待订单超过售后期再转入
        MerchantInfo merchantInfo = merchantInfoService.getByIdForUpdate(usGoodsOrder.getMerchantId());
        if (CommUtil.checkNull(merchantInfo)) {
            //平台抽成
            SysParams sysParams = sysParamsService.getByIdForUpdate(5L);
            if (!CommUtil.checkNull(sysParams)) {
                throw new ServiceException();
            }
            BigDecimal adMultiply = usGoodsOrder.getRealPrice().multiply(new BigDecimal(sysParams.getValue()));
            AdProfit adProfit = new AdProfit().setOrigin("商家商品抽成").setMoney(adMultiply);
            if (!adProfitService.save(adProfit)) {
                throw new ServiceException();
            }
            //商家分成
            BigDecimal totalProfit = usGoodsOrder.getRealPrice().subtract(adMultiply);
            //添加流水记录
            MerchantIncomeExpend merchantIncomeExpend = new MerchantIncomeExpend().setMerchantId(merchantInfo.getId()).setOrderNum(usGoodsOrder.getOrderNum()).setMoney(totalProfit).setStatus(1);
            //商家余额添加
            merchantInfo.setBalance(merchantInfo.getBalance().add(totalProfit));
            if (!merchantIncomeExpendService.save(merchantIncomeExpend)) {
                throw new ServiceException();
            }
            if (!merchantInfoService.updateById(merchantInfo)) {
                throw new ServiceException();
            }
        }


    }
}
